package com.konsung.ksdc.manager.saleservice;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.MachineNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.ImageUtils;
import com.konsung.ksdc.common.utils.PhotoUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.TakePicBottomPop;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;
import com.konsung.ksdc.manager.machine.MyMachineActivity;
import com.konsung.ksdc.manager.machine.PicViewActivity1;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 提交售后页面Activity
 * Created by Administrator on 2016/3/23 0023.
 */
public class AddProblemActivity extends BaseActivity {

    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int SELECT_PIC = 3;

    public static final String PIC_FILE = "picFile";
    public static final int PHOTO_EDIT = 10;
    public static final int RESULT_BACK = 101;
    public static final int RESULT_DELETE = 102;
    private static final int RELEVANCE_HEALTH_ONE = 4;
    @Bind(R.id.ll_add_pic)
    LinearLayout llAddPic;
    @Bind(R.id.ll_photo_container)
    LinearLayout llPhotoContainer;
    @Bind(R.id.tab_tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.btn_commit)
    Button btnCommit;
    @Bind(R.id.sp_machine)
    Spinner spMachine;
    @Bind(R.id.et_problem_desc)
    EditText etProblemDesc;
    @Bind(R.id.tv_relevance)
    TextView tvRelevance;

    private String requestMacId;
    private List<String> macNameList = new ArrayList<>();
    private List<String> macIdList = new ArrayList<>();
    private List<File> files = new ArrayList<>();

    private Uri imageUri;
    private Bitmap bitmap;
    private TakePicBottomPop popWindow;
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    clickTakePhoto();
                    break;
                case R.id.btn_album:
                    clickAlbum();
                    break;
                case R.id.btn_cancel:
                    popWindow.dismiss();
                    break;
                default:
                    break;
            }
        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    progressDialog.hide(); //隐藏缓冲条
                    break;
                case 1:
                    progressDialog.show(); //显示缓冲条
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    progressDialog.hide(); //隐藏缓冲条，回到上个页面
                    finish();
                    break;
                default:
                    break;
            }
        }
    };
    private ProgressDialog progressDialog;
    private ArrayAdapter<String> adapter;

    /**
     * 点击相册（图库）
     */
    private void clickAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PIC);
    }

    /**
     * 点击拍照
     */
    private void clickTakePhoto() {
        File outputImage = new File(Environment
                .getExternalStorageDirectory(), "test" + System
                .currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_problem);
        ButterKnife.bind(this);
        initData();
        initView();
        initEvent();
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_add_problem);
    }

    /**
     * 初始化进度条
     */
    private void initView() {
        progressDialog = new ProgressDialog(AddProblemActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.dialog_tip_loading));
        progressDialog.setCancelable(true);
    }

    /**
     * 初始化售后提交数据
     */
    private void initData() {
        tvTitle.setText(R.string.title_activity_add_problem);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new ArrayAdapter<>(AddProblemActivity.this, R.layout
                .support_simple_spinner_dropdown_item, macNameList);

        if (!RequestUtils.checkNetwork(AddProblemActivity.this)) {
            return;
        }
        loadMachineData();
    }

    /**
     * 加载该用户关联的一体机数据
     */
    private void loadMachineData() {
        RequestUtils.findRelatedMac(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(AddProblemActivity.this,
                                getString(R.string.machine_data_load_fail));
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        List<MachineNetBean> machineList = responseBean
                                .getList(new TypeToken<List<MachineNetBean>>() {
                                }.getType());
                        macNameList.clear();
                        for (MachineNetBean bean : machineList) {
                            String macName = bean.getMacName();
                            String id = bean.getId();
                            macNameList.add(macName + " - " + bean
                                    .getSerialNum());
                            macIdList.add(id);
                        }
                        List<String> macNameListReal = new ArrayList<String>(macNameList);
                        if (macNameListReal.size() > 0) {
                            adapter.clear();
                            adapter.addAll(macNameListReal);
                            spMachine.setAdapter(adapter);
                            tvRelevance.setVisibility(View.GONE);
                        } else {
                            tvRelevance.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    /**
     * 初始化售后提交页面事件
     */
    private void initEvent() {
        spMachine.setOnItemSelectedListener(new AdapterView
                .OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int
                    position, long id) {
                if (spMachine.getChildCount() > 0) {
                    if (macIdList.size() > 0) {
                        requestMacId = macIdList.get(position);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        llAddPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int childCount = llPhotoContainer.getChildCount();
                if (childCount >= 4) {
                    Toast.makeText(AddProblemActivity.this, R.string
                                    .tip_most_3_photo,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                addPhoto();
            }
        });

        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickCommit();
            }
        });
        tvRelevance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(AddProblemActivity.this, MyMachineActivity.class);
                startActivityForResult(intent, RELEVANCE_HEALTH_ONE);
            }
        });
    }

    /**
     * 点击提交
     */
    private void clickCommit() {
        if (null == macNameList || macNameList.size() <= 0) {
            ToastUtils.toastContent(AddProblemActivity.this, getString(R.string.tip_machine_null));
            return;
        }
        if (checkContentEmpty()) {
            return;
        }
        if (requestMacId == null) {
            Toast.makeText(AddProblemActivity.this, R.string.tip_machine_zero,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        progressDialog.show();
        if (files.size() <= 0) {
            String serviceContent = etProblemDesc.getText().toString().trim();
            if (requestMacId == null) {
                // ### 如果没有机器也提交故障维修 ###
                requestMacId = "";
            }
            saveSaleServiceData(NetConfig.currentEmpid, requestMacId,
                    serviceContent, "");
            return;
        }
        PostFormBuilder builder = OkHttpUtils.post();
        for (int i = 0; i < files.size(); i++) {
            if (!files.get(i).exists()) {
                Toast.makeText(AddProblemActivity.this, R.string.tip_file_error,
                        Toast.LENGTH_SHORT).show();
                return;
            }
            ImageUtils imageUtils = new ImageUtils();
            //获取根据屏幕宽高压缩后的图片
            Bitmap bitmap = imageUtils.getBitmap(files.get(i).getPath());
            byte[] bytes = imageUtils.getBitmapByte(bitmap);
            File file = new File(files.get(i).getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(bytes);
                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            builder.addFile("file", "test+" + System.currentTimeMillis() + "" +
                    ".jpg", file);
        }

        String url = NetConfig.getBasicUrl() + "uploadPicture";
        builder.url(url)
                .build()
                .execute(new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        handler.sendEmptyMessage(1);
                        String picPath = responseBean.getEntity(String.class);
                        String[] split = picPath.split("&");

                        String serviceContent = etProblemDesc.getText()
                                .toString().trim();
                        String empId = NetConfig.currentEmpid;
                        saveSaleServiceData(empId, requestMacId,
                                serviceContent, picPath);
                    }
                });
    }

    /**
     * 校验文字信息是否为空
     * @return true为空
     */
    private boolean checkContentEmpty() {
        String problemDesc = etProblemDesc.getText().toString().trim();
        if (TextUtils.isEmpty(problemDesc)) {
            Toast.makeText(this, R.string.tip_problem_desc_empty, Toast
                    .LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * 提交售后
     * @param empId 账号empId
     * @param requestMacId 一体机机器id
     * @param serviceContent 售后问题描述
     * @param picPath 图片路径
     */
    private void saveSaleServiceData(String empId, String requestMacId,
            String serviceContent, String picPath) {

        if (!RequestUtils.checkNetwork(AddProblemActivity.this)) {
            hideDialog();
            return;
        }
        RequestUtils.saveSaleService(empId, requestMacId, serviceContent,
                picPath, new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            Toast.makeText(AddProblemActivity.this, R.string
                                            .tip_commit_success,
                                    Toast.LENGTH_SHORT).show();
                            handler.sendEmptyMessage(2); // 上传成功
                        }
                        handler.sendEmptyMessage(0);
                    }
                });
    }

    /**
     * 点击添加图片，弹出popwindow。选择图库或拍照的图片。
     */
    private void addPhoto() {
        popWindow = new TakePicBottomPop(
                AddProblemActivity.this, itemsOnClick);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        popWindow.showAtLocation(AddProblemActivity.this.llPhotoContainer,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
            data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //startPhotoZoom(imageUri);
                    File file = new File(PhotoUtils.getPath(this, imageUri));
                    files.add(file);
                    addIvPic(file);
                }
                break;

            case CROP_PHOTO:
                try {
                    if (resultCode == RESULT_OK) {
                        final File file = new File(PhotoUtils.getPath(this,
                                imageUri));
                        files.add(file);
                        addIvPic(file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case PHOTO_EDIT:
                // ### 点击图片按钮查看图片 ###
                if (resultCode == RESULT_DELETE) {
                    final File picFile = (File) data.getSerializableExtra(PIC_FILE);
                    files.remove(picFile);
                    llPhotoContainer.removeAllViews();

                    for (final File file : files) {
                        addIvPic(file);
                    }
                }
                break;
            case SELECT_PIC:
                if (resultCode == RESULT_OK) {
                    //startPhotoZoom(data.getData());
                    File file = new File(PhotoUtils.getPath(this, data
                            .getData()));
                    files.add(file);
                    addIvPic(file);
                }
                break;
            case RELEVANCE_HEALTH_ONE:
                loadMachineData();
                break;
            default:
                break;
        }
    }

    /**
     * ivcontainer中添加imageview（图片）。
     * @param file 文件对象
     */
    private void addIvPic(final File file) {
        ImageView ivPic = new ImageView(AddProblemActivity.this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(DensityUtils
                .dp2px(this, 90), DensityUtils.dp2px(this, 90));
        ivPic.setLayoutParams(lp);
        ivPic.setPadding(5, 5, 5, 5);
        ivPic.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageUtils imageUtils = new ImageUtils();
        bitmap = imageUtils.ratio(file.getPath());
        ivPic.setImageBitmap(bitmap);
        ivPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickPic(file);
            }
        });
        llPhotoContainer.addView(ivPic, 0);
    }

    /**
     * 使用打开图片文件
     * @param file 点击的图片文件对象
     */
    private void clickPic(File file) {
        Intent intent = new Intent(AddProblemActivity.this, PicViewActivity1
                .class);
        intent.putExtra(PIC_FILE, file);
        startActivityForResult(intent, PHOTO_EDIT); // 10 --> requestCode
    }

    /**
     * 隐藏dialog
     */
    private void hideDialog() {
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }

    @Override
    protected void onDestroy() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
        super.onDestroy();
    }
}
